<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <title>h264文件找nalu</title>
</head>

<body>

    <input type="file" id="fileInput" />

    <div id="arrayContainer"></div>

    <script>

        const fileInput = document.getElementById("fileInput");

        fileInput.addEventListener("change", (e) => {
            const file = e.target.files[0]; // 获取用户选择的文件
            const reader = new FileReader();
            var typedAr;

            // 读取文件内容（文本格式）
            //reader.readAsText(file);
            reader.readAsArrayBuffer(file);
            //reader.readAsBinaryString(file);
            //读取完文件以后
            reader.onload = () => {
                typedAr = new Uint8Array(reader.result);

                console.log("文件长度：", typedAr.byteLength);
                if (!(typedAr.byteLength > 0)) return;
                var b1 = -1; // byte before one
                var b2 = -2; // byte before two
                var nalStartPos = new Array();

                for (var i = 0; i < typedAr.byteLength; i += 2) {
                    var b_0 = typedAr[i];
                    var b_1 = typedAr[i + 1];

                    //连续三个0
                    if (b1 == 0 && b_0 == 0 && b_1 == 0) {
                        console.log("找到nalu，位置", i - 1);
                        nalStartPos.push(i - 1);
                    }
                    //连续三个0和一个1
                    else if (b_1 == 1 && b_0 == 0 && b1 == 0 && b2 == 0) { 
                        console.log("找到nalu，位置", i - 2);
                        nalStartPos.push(i - 2);
                    }
                    b2 = b_0;
                    b1 = b_1;
                }

                var nals = new Array();
                //多个nalu，进行分割
                if (nalStartPos.length > 1) {
                    var i;
                    for (i = 0; i < nalStartPos.length -1; ++i) {
                        nals.push(typedAr.subarray(nalStartPos[i], nalStartPos[i + 1]));
                        console.log("nalu", i, "长度", nals[i].byteLength);
                    }
                    nals.push(typedAr.subarray(nalStartPos[i], typedAr.byteLength));
                    console.log("nalu", i, "长度", nals[i].byteLength);

                } else { //单个nalu直接压进去
                    nals.push(typedAr);
                    console.log("nalu", 0, "长度", nals[0].byteLength);
                }
            };

        });



    </script>
</body>

</html>
